package org.deltaset.samples.petclinic.base;

import org.deltaset.meta.EntityResolver;
import org.deltaset.meta.extension.RepositoryProvider;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;

/**
 *
 * @author dmakariev
 */
public class RepositoryProviderImpl implements RepositoryProvider, BeanFactoryAware {

    private BeanFactory beanFactory;

    @Override
    public Class defaultRepositoryClass() {
        return ModelRepository.class;
    }

    @Override
    public Object locateRepository(final Class serviceClass, final Class entityClass) {
        // final ApplicationContext ctx = FacesContextUtils.getWebApplicationContext(FacesContext.getCurrentInstance());
        try {

            final Object service = getBeanFactory().getBean(serviceClass);
            return service;
        } catch (NoSuchBeanDefinitionException ex) {
        } catch (BeansException ex) {
        }
        final BaseRepository baseRepository = getBeanFactory().getBean(BaseRepository.class);
        return new BaseModelRepository(baseRepository, entityClass);
    }

    @Override
    public EntityResolver createEntityResolver() {
        return new EntityResolverImpl();
    }

    private BeanFactory getBeanFactory() {
        return beanFactory;
    }

    @Override
    public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
        this.beanFactory = beanFactory;
    }
}
